//
//  OneSelectorCell.swift
//  Aiwei
//
//  Created by zhu xietong on 2017/11/9.
//  Copyright © 2017年 zhu xietong. All rights reserved.
//

import Foundation
import Eelay
typealias FieldChangeValue = (_ value:Any,_ view:Any)->Void



open class FOneSelectorCell: FieldCell {
    
    override open func addLayoutRules() {
        super.addLayoutRules()
        _ = selector.valueL.ui.right
        contentView.eelay = [
            [titleL,FieldCell.name_width.+1000],
            [selector,[ee.T.B],[titleL,ee.R,ee.L,8],[rightIcon,ee.L,ee.R,-8]],
        ]
        selector.valueL.textAlignment = .right
        let tap = UITapGestureRecognizer(target: self, action: #selector(openSelector))
        contentView.addGestureRecognizer(tap)
    }
    public let selector = FOneSelectorFeild()
    
    @objc public func openSelector() {
        selector.selecctAction()
    }
    
    override open func mo_model_reload() {
        
//        contentView.fillData(model: mo.model)
        selector.controller = self.content_controller
        if let f = DataNode<NSMutableDictionary>.path(node: "\(FK.fields).0", mo.model)
        {
            selector.mo.model = f
            return
        }
        if let f = DataNode<NSMutableDictionary>.path(node: "\(FK.field)", mo.model)
        {
            selector.mo.model = f
            return
        }
    }
    
    
}



open class FOneSelectorFeild: FieldView {
    public let valueL = UILabel()
    public var idNode = "id"
    public var nameNode = "name"
    
    
    override open func addLayoutRules() {
        let bt = UIButton()
        self.eelay = [
            [valueL,[ee.Y.R],[ee.L,0.+1000]],
            [bt,[ee.T.L.B.R]]
        ]
        valueL.textColor = ._foreground
        valueL.font = UIFont.systemFont(ofSize: 15)
        bt.addTarget(self, action: #selector(selecctAction), for: .touchUpInside)
        
    }
    
    @objc open func selecctAction() {
//        print("=====IIIIS",self.mo.controller)
        if mo.model[FK.editble,FK.YES] == FK.NO
        {
            return
        }
        let ctr = FOneSelector<FOneSelector.Cell>()
        ctr.title = self.place_holder
        weak var wself = self
        let idN = self.idNode
        let nameN = self.nameNode
        
        
        ctr.confirm = { obj in
            
            wself?.mo.model[FK.valueDisplay] = obj[nameN,""]
            wself?.save(obj[idN,""])
            wself?.mo_model_reload()
            guard let ws = wself else {
                return
            }
            if let block = ws.mo.model[FK.changeBlock] as? FieldChangeValue{
                block(obj,ws)
            }
            
        }
        ctr.mo.model = self.mo.model
        self.mo.controller?.present(ctr, animated: false, completion: nil)
    }
    
    
    
    open var valueDispaly:String{
        get{
            var valueD = ""
            let value = mo.model[FK.value,""]
            //            if valueD.len < 1 && value.len < 1{
            //                return ""
            //            }
            //
            //            if valueD.len < 1
            //            {
            let list = DataNode.path(node: FK.options, mo.model, value: NSMutableArray())
            for one in list{
                if let dict = one as? NSMutableDictionary
                {
                    if dict[idNode,""] == value
                    {
                        valueD = dict[nameNode,""]
                        break
                    }
                }
                continue
            }
            //            }
            return valueD
        }
    }
    
    open override func get_string_value() -> String {
        return mo.model["value",""]
    }
    
    open override func mo_model_reload() {
        
        let value = valueDispaly
        
        if value.len < 1
        {
            
            
            valueL.ui.font(font:FieldView.valueStyle.font).text(color: valueColor)
            valueL.text = place_holder
            valueL.ui.font(font: FieldView.holderStyle.font).text(color: holderColor)
        }
        else{
            valueL.text = value
            valueL.ui.font(font:valueFont).text(color: valueColor)
        }
    }
}

open class FOneSelector<cellType:JoTableCell>: GesSideController,TableVConfig {
    public var idNode = "id"
    public var nameNode = "name"
    
    public var buttonName:String = "关闭".loc
    public func touch(cell: Any, actionID: String, model: NSMutableDictionary) {
    }
    
    public var showCloseButtton = true
    public var showBottomButtton = false
    public var autoClose = false

    open override var backgroundView: UIView{
        let v = UIView()
        v.backgroundColor = ._background
        return v
    }
    public var confirm:(_ item:NSMutableDictionary) ->Void = {_ in}
    public let tableView = UITableView(frame: [0], style: .plain)
    open var sections:TP.section{
        get{
            let options = DataNode.path(node: FK.options, mo.model, value: NSMutableArray())
            var list = [[String:Any]]()
            let value = mo.model[FK.value,"XXXXXX"]
            
            print("ksksk0900--",mo.model)
            let nameN = self.nameNode
            let idN = self.idNode
            options.list { (dict:NSMutableDictionary, i) in
                var obj = ["id":dict[idN,""],"name":dict[nameN,""],"__raw__":dict] as [String : Any]
                print("----00cc1",value)
                if value == dict[idNode,""]
                {
                    print("----00cc99",dict[idNode,""])

                    obj[FK.selected] = FK.YES
                }
                list.append(obj)
            }
            let sec:TP.section = [
                //                FormTypes.types(names: ["first","second","third"])
                list
            ]
            return sec
        }
    }
    
    public var selector:TP.selector = [
        "<section0>":cellType.self,
        ]
    
    public let bar = UIButton()
    public let nameL = UILabel()
    
    public let barBack = UIView()
    public let bottomBtn = UIView()
    
    
    open func layTable(tableView:UIView)
    {
        let line = UIView()
        let safeDistance = MoUIAdapter.safeInset.bottom
        bar.isUserInteractionEnabled = false
     
        barBack.eelay = [
            [bar,[ee.T.L.R,[5,AppTheme.edge,-AppTheme.edge]],"40".+1000,[ee.B,-(safeDistance + 5)]],
            [bottomBtn,[bar,ee.T.L.B.R]],
        ]
        
        
//        bar.setContentConstrainToHighLever()
        
        if(showBottomButtton){
            jo_contentView.eelay = [
                [nameL,[ee.T.L.R,[16,10,-10]],"20"],
                [barBack,[ee.L.R.B],"40"],
                [tableView,[ee.L.R,[10,-10]],[nameL,ee.B,ee.T,16],[barBack,ee.T,ee.B]],
                //            [line,[ee.T.B.R],0.6],
            ]
        }else{
            jo_contentView.eelay = [
                [nameL,[ee.T.L.R,[16,10,-10]],"20"],
    //            [bar,[ee.L.R],"40",[ee.B,-safeDistance]],
                [tableView,[ee.L.R,[10,-10]],[nameL,ee.B,ee.T,16],[ee.B,-safeDistance]],
                //            [line,[ee.T.B.R],0.6],
            ]
        }
        
        line.backgroundColor = ._separator
        
        
        if showCloseButtton{
            let bt = UIButton()
            jo_contentView.eelay = [
                [bt,[nameL,ee.Y],[ee.R,-10]],
            ]
            bt.ui.nimage(UIImage(named: "delete_tag")).padding(insets: [10,10])
            bt.addTarget(self, action: #selector(close), for: .touchUpInside)
        }
    }
    
    
    override open func viewDidLoad() {
        self.side = .bottom(height: 400)
        super.viewDidLoad()
        layTable(tableView: tableView)
        self.configTables(tables: tableView)
        tableView.buildDynamicHeight(height: 44)
        tableView.separatorStyle = .none
        tableView.load(sections: sections, selector: selector)
        tableView.backgroundColor = .clear
        tableView.reloadData()
        jo_contentView.backgroundColor = .clear
        self.gestureAble = true
        
        _ = mo.model["style.tiny",UIColor.main_hex]
        
            bar.ui.buttonColor(color: ._tint).ncolor(hex: "#fff").font(size: 15).ntitle(title: buttonName)
//            barBack.backgroundColor = ._tint
        
        
        bar.addTarget(self, action: #selector(bottomAction), for: .touchUpInside)
        bottomBtn.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(bottomAction)))
        let name = self.title ?? "请选择".loc
        _ = nameL.ui.center.font16.text(name)
    }
    
    public var nextAction:()->Bool = { return true}
    
    @objc open func bottomAction() {
        if nextAction()
        {
            close()
        }
    }
    
    
    open func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let list = DataNode.path(node: "section0", tableView.model, value: NSMutableArray())
        list.list { (dict:NSMutableDictionary, i) in
            dict[FK.selected] = FK.NO
        }
        guard let data = tableView.cellData(at: indexPath) else {
            return
        }
        data[FK.selected] = FK.YES
        self.confirm(data)
        tableView.reloadData()
        if autoClose{
            self.close()
        }
    }
    
//    override open var backgroundView: UIView{
//        let blurView = UIVisualEffectView()
//        let sty = UIBlurEffect.Style.extraLight
//        let blurEffect = UIBlurEffect(style: sty)
//        blurView.effect = blurEffect
//        return blurView
//    }
//
    
    
    override open func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
}

extension FOneSelector
{
    public class Cell: JoTableCell {
        public let nameL = UILabel()
        public let selectIconV = UIImageView()
        public override func addLayoutRules() {
            contentView.eelay = [
                [nameL,[ee.T.L.B.R,[16,10,-16,-60]],"20"],
                [selectIconV,[ee.Y.R,[0,-10]],"20",20],
                [__line,[ee.L.B.R,[10,0,-10]],"\(TP.separatorHeight)"]
            ]
            contentView.backgroundColor = .clear
            backgroundColor = .clear
            __line.backgroundColor = UIColor._separator
            _ = nameL.ui.font13.text(color: ._foreground)
            
        }
        public override func mo_model_reload() {
            
            nameL.text = mo.model["name",""]
            if mo.model["selected","NO"] == "YES"
            {
                selectIconV.image = UIImage(named:"radio_check_s")
            }
            else{
                selectIconV.image = UIImage(named:"radio_check_n")
            }
        }
    }
}

